<?php

namespace app\common\func;

use think\Db;

/**
 * 表 - 操作
 * Class
 * @package
 */
class Tables
{
	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;


	/**
	 * 默认配置
	 * @var array
	 */
	protected $config  = [
		"prefix" 		=> "fd_",
		"balance_log" 	=> "balance_log" 	// 余额变更
	];

	/**
	 * 实例化
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 信息存储表
	 *
	 * @param string $tables
	 * @param array $option
	 * @return boolean|int
	 */
	public function general_storage($table, $option,  $comment = "新增表")
	{
		if (!empty($table) && is_array($option)) {
			$arrKey = array_keys($option);
			// 创建表
			$check = $this->check($table);
			!$check && $table = $this->general_create_table($table, $arrKey, $comment);
			if ($table) {
				// 查看存储字段是否存在
				$this->check_table_colums($table, $arrKey);
				// 存储
				$id = Db::name($table)->insertGetId($option);
				if ($id) {
					return $id;
				}
			}
		}
		return false;
	}

	/**
	 * 创建 - 信息存储表
	 *
	 * @param string $tables
	 * @param array $option
	 * @return void
	 */
	public function general_create_table(string $tables, array $option, $comment)
	{
		$table = "";
		try {
			$createTab = $tables;
			$res = $this->check($createTab);
			if (!$res) {
				$str = "`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID',\n";
				for ($i = 0; $i < count($option); $i++) {
					$str .= "`" . $option[$i] . "` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL ,\n";
				}
				$str .= "PRIMARY KEY (`id`) USING BTREE\n";
				$table = $this->create($createTab, $str, 'InnoDB',  $comment);
			} else {
				$table = $createTab;
			}
		} finally {
			return $table;
		}
	}

	/**
	 * 微信 - 支付回调信息存储表
	 *
	 * @param [type] $tables
	 * @param [type] $proname
	 * @return void
	 */
	public function wx_pay_notic_table(string $tables = "", array $option = [])
	{
		$table = "";
		try {
			$createTab = $tables;
			$res = $this->check($createTab);
			if (!$res) {
				$str = "`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID',\n";
				for ($i = 0; $i < count($option); $i++) {
					$str .= "`" . $option[$i] . "` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL ,\n";
				}
				$str .= "PRIMARY KEY (`id`) USING BTREE\n";
				$table = $this->create($createTab, $str, 'InnoDB',  "微信支付信息记录");
			} else {
				$table = $createTab;
			}
		} finally {
			return $table;
		}
	}

	/**
	 * 创建余额变更明细
	 */
	public function balance_log()
	{
		$table = "";
		$q = $this->quarter_qs(date("Y"), date("m"));
		$create_table = $this->config["balance_log"] . "_" . $q;
		$res = $this->check($create_table);
		if (!$res) {
			$str = "`id` int(11) NOT NULL AUTO_INCREMENT,
					`main_id` int(11) NOT NULL COMMENT '商户id',
					`balance_type_id` tinyint(2) NOT NULL COMMENT '余额类型:1=分润,2=流量卡,3=达标,4=借款,5=还款,6=赠送,7=提现,8=认购,9=调价，10=采购',
					`earn_type` tinyint(1) DEFAULT '1' COMMENT '余额类型:1=收入,2=支出',
					`mome` text COMMENT '备注',
					`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态:1=已结算,2=未结算',
					`product_id` int(11) DEFAULT '0' COMMENT '产品ID',
					`before` decimal(11,2) DEFAULT '0.00' COMMENT '变更前',
					`money` decimal(12,2) DEFAULT '0.00' COMMENT '变更金额',
					`after` decimal(11,2) DEFAULT '0.00' COMMENT '变更后',
					`times` int(11) DEFAULT '0' COMMENT '变更时间YY-mm-dd',
					`create_time` int(11) DEFAULT '0' COMMENT '创建时间',
					PRIMARY KEY (`id`) USING BTREE";
			$table = $this->create($create_table, $str, 'InnoDB', $q . "余额日志");
		} else {
			$table = $create_table;
		}
		return $table;
	}

	/**
	 * 季度
	 *
	 * @param string $year
	 * @param string $months
	 * @return void
	 */
	public  function quarter_qs($year, $months)
	{
		$qs = "";
		$year = empty($year) ? date("Y") : $year;
		// 初始化季度数组
		for ($i = 1; $i <= 4; $i++) {
			for ($k = ($i * 3 - 2); $k <= ($i * 3); $k++) {
				if ($months == $k) {
					$qs =  $year . "_" . $i;
					break;
				}
			}
		}
		return $qs;
	}

	/**
	 * 创建数据表
	 *
	 * @param string $createTable   创建表名
	 * @param string $sqlStr		创建字段
	 * @param string $comment		表字段
	 * @return string
	 */
	public function create($createTable, $sqlStr, $engine = "InnoDB",  $comment = "数据表")
	{
		$table = "";
		try {
			if (!empty($createTable) && !empty($sqlStr)) {
				# 创建验证
				$isExist =  $this->check($createTable);
				if (!$isExist) {
					$sql_str = "CREATE TABLE `" . $this->config["prefix"] . $createTable . "` (" . $sqlStr . ") ENGINE=" . $engine . " DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='" . $comment . "';";
					Db::execute($sql_str);
				}
				# 是否创建成功
				$isExist = $this->check($createTable);
				if ($isExist) {
					$table = $createTable;
				}
			}
		} finally {
			return $table;
		}
	}

	/**
	 * 查看表字段是否存在
	 */
	public function check_table_colums($table, $fields)
	{

		foreach ($fields as $v) {
			$sql = "SELECT count(*) con FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='pro' AND TABLE_NAME='" . $this->config["prefix"] . $table . "' AND COLUMN_NAME = '{$v}';";
			$result = Db::query($sql);
			if (!$result[0]['con']) {
				$alter = "alter table " . $this->config["prefix"] . $table . " add column `{$v}` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL;";
				Db::execute($alter);
			}
		}
	}

	/**
	 * 查看表是否存在
	 *
	 * @param [type] $table
	 * @return boolean
	 */
	public function check($table)
	{
		return Db::query("SHOW TABLES like '" . $this->config["prefix"] . $table . "'");
	}
}
